package utils

import (
	"fmt"
	"github.com/beego/beego/v2/core/logs"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

type DecoratorHandler func(http.HandlerFunc) http.HandlerFunc

func MiddlewareHandlerFunc(hp http.HandlerFunc, decors ...DecoratorHandler) http.HandlerFunc {
	for d := range decors {
		dp := decors[len(decors)-1-d]
		hp = dp(hp)
	}
	return hp
}

func VerifyHeader(h http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		token := r.Header.Get("token")

		if token == "" {
			fmt.Fprintf(w, r.URL.Path+" response: Not Logged in")
			return
		}
		h(w, r)
	}
}

func Pong(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, r.URL.Path+"response: pong")
	return
}

// HttpRequest 请求服务
func HttpRequest(method string, rurl string, postArgs map[string]string, headerArgs map[string]string) ([]byte, error) {
	var clusterinfo = url.Values{}
	for key, value := range postArgs {
		clusterinfo.Add(key, value)
	}
	data := clusterinfo.Encode()
	reader := strings.NewReader(data)
	request, err := http.NewRequest(method, rurl, reader)
	if err != nil {
		logs.Debug(err.Error())
		return nil, err
	}
	for key, value := range headerArgs {
		request.Header.Set(key, value)
	}
	client := http.Client{}
	resp, err := client.Do(request)
	logs.Debug(resp, err)
	if err != nil {
		logs.Debug(err.Error())
		return nil, err
	}
	respBytes, _ := ioutil.ReadAll(resp.Body)
	return respBytes, nil
}

//func main()  {
//	http.HandleFunc("/api/asong/ping",MiddlewareHandlerFunc(Pong,VerifyHeader))
//	err := http.ListenAndServe(":8080", nil)
//	if err != nil {
//		log.Fatal("ListenAndServe: ", err)
//	}
//}
